package cn.numeron.wandroid

import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.core.view.iterator
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import cn.numeron.discovery.Discoveries
import com.google.android.material.navigation.NavigationBarView
import cn.numeron.common.frame.SubpageFactory
import cn.numeron.common.viewbinding.viewBinding
import cn.numeron.wandroid.databinding.FragmentHealthyBinding
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class WandroidFragment : Fragment(R.layout.fragment_healthy) {

    private val listeners = Listeners()

    private val viewBinding: FragmentHealthyBinding by viewBinding()

    private val subpageFactories by lazy {
        //获取可用于主页的页面工厂类，通过工厂类创建对应的Fragment实例
        Discoveries.getAllInstances<SubpageFactory>().sortedBy(SubpageFactory::index)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //创建底部菜单
        for (factory in subpageFactories) {
            factory.createMenuItem(viewBinding.healthyNavigationView.menu)
        }
        viewBinding.healthyNavigationView.setOnItemSelectedListener(listeners)
        //加载ViewPager
        viewBinding.healthyViewPager.adapter = HealthyViewPagerAdapter()
        viewBinding.healthyViewPager.registerOnPageChangeCallback(listeners)
    }

    private inner class HealthyViewPagerAdapter : FragmentStateAdapter(this) {

        override fun getItemCount(): Int = subpageFactories.size

        override fun createFragment(position: Int): Fragment {
            return subpageFactories[position].createFragment()
        }

    }

    private inner class Listeners : ViewPager2.OnPageChangeCallback(),
        NavigationBarView.OnItemSelectedListener {

        override fun onPageSelected(position: Int) {
            val menuItem = viewBinding.healthyNavigationView.menu.getItem(position)
            viewBinding.healthyNavigationView.selectedItemId = menuItem.itemId
        }

        override fun onNavigationItemSelected(item: MenuItem): Boolean {
            val position = viewBinding.healthyNavigationView
                .menu.iterator().asSequence().indexOf(item)
            if (position > -1) {
                viewBinding.healthyViewPager.currentItem = position
            }
            return position > -1
        }

    }

}